package com.jindy.module.oaContractApply.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jindy.activiti.service.IProcessService;
import com.jindy.common.constant.Constants;
import com.jindy.common.exception.base.BaseException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.common.utils.StringUtils;
import com.jindy.jpush.utils.UniJpushUtils;
import com.jindy.module.approvalRecord.domain.ApprovalRecord;
import com.jindy.module.approvalRecord.mapper.ApprovalRecordMapper;
import com.jindy.module.jpush.mapper.JpushMapper;
import com.jindy.module.oaContractApply.domain.SyContractInfoWe;
import com.jindy.module.oaContractApply.service.ISyContractInfoOtherService;
import com.jindy.module.oaContractApply.service.ISyContractInfoWeService;
import com.jindy.module.oaDepartTurnApply.domain.SyOaDepartTurn;
import com.jindy.module.oaDepartTurnApply.mapper.SyOaDepartTurnMapper;
import com.jindy.module.oaDepartTurnApply.service.impl.SyOaDepartTurnServiceImpl;
import com.jindy.module.oaEvectionApproval.domain.SyOaEvection;
import com.jindy.module.oacopy.service.ISyOaCopyService;
import com.jindy.module.oacopyconfig.domain.SyOaCopyConfig;
import com.jindy.module.oacopyconfig.mapper.SyOaCopyConfigMapper;
import com.jindy.module.serialNum.service.ISySerialNumTService;
import com.jindy.module.syTableRecord.service.ISyTableRecordTService;
import com.jindy.system.domain.SysUserRoleDeptInfo;
import com.jindy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jindy.module.oaContractApply.mapper.SyOaContractMapper;
import com.jindy.module.oaContractApply.domain.SyOaContract;
import com.jindy.module.oaContractApply.service.ISyOaContractService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 智能合同审批Service业务层处理
 * 
 * @author jindy
 * @date 2023-06-29
 */
@Service
public class SyOaContractServiceImpl implements ISyOaContractService 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SyOaContractServiceImpl.class);

    @Autowired
    private SyOaContractMapper syOaContractMapper;

    @Autowired
    private IProcessService processService;

    /**
     * 抄送Service
     */
    @Resource
    private ISyOaCopyService syOaCopyService;

    /**
     * 配置表
     */
    @Resource
    private SyOaCopyConfigMapper syOaCopyConfigMapper;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ISySerialNumTService serialNumTService;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ApprovalRecordMapper approvalRecordMapper;

    /**
     * 用户Service
     */
    @Resource
    private ISysUserService sysUserService;

    /**
     * 设备Mapper
     */
    @Resource
    private JpushMapper jpushMapper;

    /**
     * 存储表Service
     */
    @Resource
    private ISyTableRecordTService iSyTableRecordTService;

    @Resource
    private ISyContractInfoWeService iSyContractInfoWeService;

    @Resource
    private ISyContractInfoOtherService iSyContractInfoOtherService;

    /**
     * 查询智能合同审批
     * 
     * @param id 智能合同审批主键
     * @return 智能合同审批
     */
    @Override
    public SyOaContract selectSyOaContractById(Long id)
    {
        SyOaContract syOaContract=new SyOaContract();
        syOaContract=syOaContractMapper.selectSyOaContractById(id);

        if(syOaContract.getContractWeId() != null && !syOaContract.getContractWeId().equals("")) {
            String[] weId = syOaContract.getContractWeId().split(",");
            Long[] ids = new Long[weId.length];
            for (int j = 0; j < weId.length; j++) {
                ids[j] = Long.valueOf(weId[j]);
            }
            syOaContract.setSyContractInfoWeList(iSyContractInfoWeService.selectSyContractInfoWeListByIds(ids));
        }

        if(syOaContract.getContractOtherId() != null && !syOaContract.getContractOtherId().equals("")) {
            String[] otherId = syOaContract.getContractOtherId().split(",");
            Long[] ids = new Long[otherId.length];
            for (int j = 0; j < otherId.length; j++) {
                ids[j] = Long.valueOf(otherId[j]);
            }
            syOaContract.setSyContractInfoOtherList(iSyContractInfoOtherService.selectSyContractInfoOtherListByIds(ids));
        }

        return syOaContract;
//        return syOaContractMapper.selectSyOaContractById(id);
    }

    /**
     * 查询智能合同审批列表
     * 
     * @param syOaContract 智能合同审批
     * @return 智能合同审批
     */
    @Override
    public List<SyOaContract> selectSyOaContractList(SyOaContract syOaContract)
    {
        if (!SecurityUtils.isAdmin(SecurityUtils.getLoginUser().getUser().getUserId())){
            syOaContract.setCreateBy(SecurityUtils.getUsername());
        }
        List<SyOaContract> list = syOaContractMapper.selectSyOaContractList(syOaContract);

        list=this.switchSyWe(list);
        list=this.switchSyOther(list);

        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
//        return syOaContractMapper.selectSyOaContractList(syOaContract);
    }

    /**
     * 新增智能合同审批
     * 
     * @param syOaContract 智能合同审批
     * @return 结果
     */
    @Override
    public int insertSyOaContract(SyOaContract syOaContract)
    {
        // 生成流水单号
        String serialNum = serialNumTService.generateSerialNum("ZNHTSP");
        if (StringUtils.isBlank(serialNum)) {
            throw new BaseException("新增智能合同审批-获取智能合同单号失败");
        }

        //保存相应的我方合同信息表id
        String ids="";
        if(syOaContract.getSyContractInfoWeList() != null && syOaContract.getSyContractInfoWeList().size()>0){
            ids=this.myTest1(syOaContract);
            syOaContract.setContractWeId(ids);
        }

        //保存相应的对方合同信息表id
        String ids1="";
        if(syOaContract.getSyContractInfoOtherList() != null && syOaContract.getSyContractInfoOtherList().size()>0){
            ids1=this.myTest2(syOaContract);
            syOaContract.setContractOtherId(ids);
        }

        //获取申请人信息
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        syOaContract.setApplyUserId(userId.toString());
        syOaContract.setApplyUserName(SecurityUtils.getLoginUser().getUser().getUserName());

        //获取申请时间
        syOaContract.setApplyTime(DateUtils.getNowDate());

        syOaContract.setSerialNum(serialNum);
        syOaContract.setBusinessStatus(Constants.DRAFT);
        syOaContract.setCreateTime(DateUtils.getNowDate());
        iSyTableRecordTService.saveEntityAndTable(syOaContract,serialNum);
        return syOaContractMapper.insertSyOaContract(syOaContract);
    }

    /**
     * 修改智能合同审批
     * 
     * @param syOaContract 智能合同审批
     * @return 结果
     */
    @Override
    public int updateSyOaContract(SyOaContract syOaContract)
    {
        syOaContract.setUpdateTime(DateUtils.getNowDate());
        return syOaContractMapper.updateSyOaContract(syOaContract);
    }

    /**
     * 批量删除智能合同审批
     * 
     * @param ids 需要删除的智能合同审批主键
     * @return 结果
     */
    @Override
    public int deleteSyOaContractByIds(Long[] ids)
    {
        return syOaContractMapper.deleteSyOaContractByIds(ids);
    }

    /**
     * 删除智能合同审批信息
     * 
     * @param id 智能合同审批主键
     * @return 结果
     */
    @Override
    public int deleteSyOaContractById(Long id)
    {
        return syOaContractMapper.deleteSyOaContractById(id);
    }

    //我方合同信息分条插入，记录id
    public String myTest1(SyOaContract syOaContract){
        String ids="";
        for (int i=0;i<syOaContract.getSyContractInfoWeList().size();i++){
            iSyContractInfoWeService.insertSyContractInfoWe(syOaContract.getSyContractInfoWeList().get(i));
            ids+=syOaContract.getSyContractInfoWeList().get(i).getId()+",";
        }
//        System.out.println(ids);
        return ids;
    }

    //对方合同信息分条插入，记录id
    public String myTest2(SyOaContract syOaContract){
        String ids="";
        for (int i=0;i<syOaContract.getSyContractInfoOtherList().size();i++){
            iSyContractInfoOtherService.insertSyContractInfoOther(syOaContract.getSyContractInfoOtherList().get(i));
            ids+=syOaContract.getSyContractInfoOtherList().get(i).getId()+",";
        }
//        System.out.println(ids);
        return ids;
    }

    //查询合同信息时加入我方信息
    public List<SyOaContract> switchSyWe(List<SyOaContract> list){
        for(int i=0;i<list.size();i++){
            if(list.get(i).getContractWeId() != null && !list.get(i).getContractWeId().equals("")){
                String[] id=list.get(i).getContractWeId().split(",");
                Long[] ids=new Long[id.length];
                for(int j=0;j<id.length;j++){
                    ids[j]=Long.valueOf(id[j]);
                }
                list.get(i).setSyContractInfoWeList(iSyContractInfoWeService.selectSyContractInfoWeListByIds(ids));
            }
        }
        return list;
    }

    //查询合同信息时加入对方信息
    public List<SyOaContract> switchSyOther(List<SyOaContract> list){
        for(int i=0;i<list.size();i++){
            if(list.get(i).getContractOtherId() != null && !list.get(i).getContractOtherId().equals("")){
                String[] id=list.get(i).getContractOtherId().split(",");
                Long[] ids=new Long[id.length];
                for(int j=0;j<id.length;j++){
                    ids[j]=Long.valueOf(id[j]);
                }
                list.get(i).setSyContractInfoOtherList(iSyContractInfoOtherService.selectSyContractInfoOtherListByIds(ids));
            }
        }
        return list;
    }

    /**
     * 提交申请
     *
     * @param syOaContract
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitApply(SyOaContract syOaContract) throws Exception {
        // 初始化值
        Map<String, Object> variables = createVariables(syOaContract);
        // 启动流程
        processService.submitApply(syOaContract, "contract", variables);
        // 添加抄送人
        syOaCopyService.addCopyUsers("ZNHTSP", syOaContract.getId());
        //新增审批记录
        List<Long> longs = addApprovalRecord(syOaContract, variables);
        // 通知审批人
        sendApproveMessage(longs);
        syOaContract.setBusinessStatus(Constants.APPROVE);
        updateSyOaContract(syOaContract);
    }

    /**
     * 新增审批记录
     * @param syOaContract
     * @param map
     * @return
     */
    private List<Long> addApprovalRecord(SyOaContract syOaContract, Map<String, Object> map) {
        List<Long> list = new ArrayList<>();
        int sequence = 1;
        //  发起人
        ApprovalRecord firstApprovalRecord = getApprovalRecord(syOaContract);
        firstApprovalRecord.setSequence(sequence);
        firstApprovalRecord.setApprovalStatus(Constants.COMPLETED);
        firstApprovalRecord.setTypeOperation(Constants.AGREE);
        firstApprovalRecord.setBusinessStatus(Constants.APPROVE);
        firstApprovalRecord.setApproverId(Long.valueOf(syOaContract.getApplyUserId()));
        firstApprovalRecord.setApproverName(syOaContract.getApplyUserName());
        approvalRecordMapper.insertApprovalRecord(firstApprovalRecord);

        sequence++;
        //  第二审批人
        ApprovalRecord thirdApprovalRecord = getApprovalRecord(syOaContract);
        thirdApprovalRecord.setSequence(sequence);
        thirdApprovalRecord.setApprovalStatus(Constants.APPROVE);
        String bossId=map.get("bossId").toString();
        thirdApprovalRecord.setApproverId(Long.parseLong(bossId));
        thirdApprovalRecord.setApproverName((String) map.get("boss"));
        approvalRecordMapper.insertApprovalRecord(thirdApprovalRecord);
        list.add(Long.parseLong(bossId));


        return list;
    }

    /**
     * 获取审批记录对象
     *
     * @param syOaContract
     * @return
     */
    private ApprovalRecord getApprovalRecord(SyOaContract syOaContract) {
        ApprovalRecord approvalRecord = new ApprovalRecord();
        approvalRecord.setSerialNum(syOaContract.getSerialNum());
        approvalRecord.setUserId(Long.valueOf(syOaContract.getApplyUserId()));
        approvalRecord.setOrderId(syOaContract.getId());
        approvalRecord.setUserName(syOaContract.getApplyUserName());
        approvalRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        approvalRecord.setUpdateBy(syOaContract.getApplyUserName());
        approvalRecord.setCreateBy(syOaContract.getApplyUserName());
        approvalRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        return approvalRecord;
    }

    /**
     * 逻辑流初始化
     *
     * @param syOaContract
     * @return
     */
    public Map<String, Object> createVariables(SyOaContract syOaContract) {
        Map<String, Object> var = new HashMap<>(500);

        //老板审批
        SyOaCopyConfig syOaCopyConfig = new SyOaCopyConfig();
        syOaCopyConfig.setNumber("ZNHTSP_LEADER");
        List<SyOaCopyConfig> syOaCopyConfigs = syOaCopyConfigMapper.selectSyOaCopyConfigList(syOaCopyConfig);
        if (CollectionUtils.isEmpty(syOaCopyConfigs)) {
            throw new BaseException("createVariables", "智能合同审批审批获取老板失败");
        }
        var.put("boss",syOaCopyConfigs.get(0).getCopyUserName());
        var.put("bossId",syOaCopyConfigs.get(0).getCopyUserId());

        return var;
    }

    /**
     * 给审批人推送消息
     * @param addJpushList
     */
    private void sendApproveMessage(List<Long> addJpushList) {
        try {
            List<String> addRegIds = jpushMapper.selectRegistrationIdsByUserIds(addJpushList);
            if (!CollectionUtils.isEmpty(addRegIds)){
                UniJpushUtils.sendApproveMessage(addRegIds);
            }
        } catch (Exception e) {
            LOGGER.error("智能合同审批审批人推送通知失败",e);
        }
    }

}
